package com.vipyinzhiwei.android.library.imageloader.listener;

import android.content.Context;
import android.support.v7.widget.RecyclerView;

import com.bumptech.glide.Glide;

/**
 * RecyclerView 滚动监听类，对图片加载进行判断处理
 *
 * @author vipyinzhiwei
 * @version 1.0
 */
public class PauseRecyclerViewOnScrollListener extends RecyclerView.OnScrollListener {

    private final Context mContext;
    private final boolean pauseOnScroll;
    private final boolean pauseOnFling;
    private final RecyclerView.OnScrollListener externalListener;

    /**
     * Constructor
     *
     * @param context
     * @param pauseOnScroll
     * @param pauseOnFling
     */
    public PauseRecyclerViewOnScrollListener(Context context, boolean pauseOnScroll, boolean
            pauseOnFling) {
        this(context, pauseOnScroll, pauseOnFling, null);
    }

    /**
     * Constructor
     *
     * @param context
     * @param pauseOnScroll
     * @param pauseOnFling
     * @param customListener
     */
    public PauseRecyclerViewOnScrollListener(Context context, boolean pauseOnScroll, boolean
            pauseOnFling,
                                             RecyclerView.OnScrollListener customListener) {
        this.mContext = context;
        this.pauseOnScroll = pauseOnScroll;
        this.pauseOnFling = pauseOnFling;
        this.externalListener = customListener;
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        if (mContext == null) return;

        switch (newState) {
            //停止滑动的状态
            case RecyclerView.SCROLL_STATE_IDLE:
                Glide.with(mContext).resumeRequests();
                break;
            //惯性滚动状态
            case RecyclerView.SCROLL_STATE_SETTLING:
                if (pauseOnScroll) {
                    Glide.with(mContext).pauseRequests();
                }
                break;
            //正在滚动，用户手指在屏幕上
            case RecyclerView.SCROLL_STATE_DRAGGING:
                if (pauseOnFling) {
                    Glide.with(mContext).pauseRequests();
                }
                break;
        }
        if (externalListener != null) {
            externalListener.onScrollStateChanged(recyclerView, newState);
        }
    }

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
    }
}
